package com.xiaoyu.base.view.list;

import android.graphics.Rect;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import in.srain.cube.util.LocalDisplay;

public class GridSpacingItemDecoration extends RecyclerView.ItemDecoration {

    private int spanCount;
    private int columnSpacing;
    private int rowSpacing;
    private boolean includeEdge;

    public GridSpacingItemDecoration(int spanCount, int columnSpacing, int rowSpacing, boolean includeEdge) {
        this.spanCount = spanCount;
        this.columnSpacing = LocalDisplay.dp2px(columnSpacing);
        this.rowSpacing = LocalDisplay.dp2px(rowSpacing);
        this.includeEdge = includeEdge;
    }

    public GridSpacingItemDecoration(int spanCount, int spacingWithDp, boolean includeEdge) {
        this(spanCount, spacingWithDp, spacingWithDp, includeEdge);
    }

    @Override
    public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
        int position = parent.getChildAdapterPosition(view);
        int column = position % spanCount;

        if (includeEdge) {
            outRect.left = columnSpacing - column * columnSpacing / spanCount;
            outRect.right = (column + 1) * columnSpacing / spanCount;

            if (position < spanCount) {
                outRect.top = rowSpacing;
            }
            outRect.bottom = columnSpacing;
        } else {
            outRect.left = column * columnSpacing / spanCount;
            outRect.right = columnSpacing - (column + 1) * columnSpacing / spanCount;
            if (position >= spanCount) {
                outRect.top = rowSpacing;
            }
        }
    }
}
